class PatientsController < ApplicationController
  layout "standard"

  def index
    if params[:searchOn].nil?
      @patients = Patient.paginate :conditions => ["hospice_branches.hospice_id = ?", session[:hospice_id]], 
                 :page =>params[:page], :per_page => 15, :order => 'last_name ASC',
                 :include => [:race, :diagnosis, :hospice_branch]
    else
      @patients = Patient.paginate :all, :conditions => [params[:searchOn] + " LIKE ? AND hospice_branches.hospice_id = ? ", "%#{params[:txtSearch]}%", session[:hospice_id]],
                :page => params[:page], :per_page => 15, :order => 'last_name ASC',
                :include => [:race, :diagnosis, :hospice_branch]
    end
    
    respond_to do |format|
      format.html #index.html.erb
      format.xml { render :xml => @patients}
    end
  end
  
  def show
    @patient = Patient.find(params[:id])
    
    respond_to do |format|
      format.html #show.html.erb
      format.xml { render :xml => @patient}
    end
  end
  
  def new
    @patient = Patient.new
    
    respond_to do |format|
      format.html #show.html.erb
      format.xml { render :xml => @patient}
    end
  end

  def edit
    @patient = Patient.find(params[:id])
  end

  def create
    @patient = Patient.new(params[:patient])
    @patient.hospice_id = session[:hospice_id]
    
    respond_to do |format|
      if @patient.save
        flash[:notice] = "Patient successfully created."
        format.html { redirect_to :controller=> "patients"}
        format.xml {render :xml => @patient, :status => :created, :location => @patient}
      else
        format.html { render :action => "new" }
        format.xml { render :xml => @patient.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  def update
    @patient = Patient.find(params[:id])
    @patient.hospice_id = session[:hospice_id]
    respond_to do |format|
      if @patient.update_attributes(params[:patient])
        flash[:notice] = "Patient was succesfully updated."
        format.html { redirect_to :controller=> "patients"}
        format.xml {head :ok}
      else
        format.html {render :action => "edit"}
        format.xml {render :xml => @patient.errors, :status => :unprocessable_entity}
      end
    end
    
  end
  
  def destroy
    Patient.find_by_id(params[:id]).destroy
    
    respond_to do |format|
      format.html {redirect_to :controller=> "patients"}
      format.xml { head :ok }
    end
  end
 
  protected
  def secure?
    true
  end
    
end
